library(tidyverse)
library(haven)
library(gtsummary)
library(skimr)
library(dplyr)
library(flextable)
library(installr)
library(ggplot2)
library(bibliometrix) 
library(formattable)
library(tableHTML)
# https://www.bibliometrix.org/vignettes/Introduction_to_bibliometrix.html
getwd()
# file<- c('savedrecs.txt','savedrecs1.txt','savedrecs2.txt')
filere<- c('savedrecsre1.txt','savedrecsre2.txt','savedrecsre3.txt','savedrecsre4.txt','savedrecsre5.txt')
# M <- convert2df(file = file, dbsource = "wos", format = "plaintext")
M <- convert2df(file = filere, dbsource = "wos", format = "plaintext")
#删除2023年数据
M<- M[which(M$PY!='2023'),]


# 删除  meeting abstracts, proceedings papers, 
# book chapters, editorials, letters, news, etc
M<- M[which(M$DT!='ARTICLE; BOOK CHAPTER'),]
M<- M[which(M$DT!='REVIEW; BOOK CHAPTER'),]
results <- biblioAnalysis(M, sep = ";")
options(width=100)
S <- summary(object = results, k = 10, pause = FALSE)

#国家发文数
Countries <-as.data.frame(results$Countries)
# 年发文数
yearCount <-S$AnnualProduction
colnames(yearCount)<- c('year','count')
yearCount$year <- as.numeric(as.character(yearCount$year))
yearCount$count <- as.numeric((yearCount$count))
# 图1A 
Cairo::CairoTIFF(file="Figure2A.tiff", width=8, height=8,units="in",dpi=150)
ggplot(yearCount,aes(x=year,y=count))+geom_line()
dev.off()
# pic2b
# https://blog.csdn.net/qq_41504254/article/details/111038887
world <- map_data("world")
countriesMap <-Countries

countriesMapTop10 <- countriesMap[c(1:10),]

countriesMapTop10$act_rate <- ifelse(countriesMapTop10$Freq>500,'>500',
                                     ifelse(countriesMapTop10$Freq>=200&countriesMapTop10$Freq<500,'200-500',
                                            ifelse(countriesMapTop10$Freq>=100&countriesMapTop10$Freq<199,'100-199',
                                                   ifelse(countriesMapTop10$Freq>=50&countriesMapTop10$Freq<99,'50-99','<49'))))
world$region<-toupper(world$region)

world %>% left_join(countriesMapTop10, by = c("region" = "Tab")) -> act_world_map
act_world_mapback <- act_world_map
act_world_map$act_rate <- ifelse(is.na(act_world_map$act_rate),"<49",act_world_map$act_rate)
Cairo::CairoTIFF(file="Figure2B.tiff", width=8, height=8,units="in",dpi=150)
ggplot(data = act_world_map, aes(x = long, y = lat, group = group)) + 
  geom_polygon(aes(fill= act_rate), colour = "white") +
  # 添加绘制国家边界线
  geom_path(data = world, aes(x = long, y = lat, group = group), 
            color = "grey", linewidth = 0.05) +
  theme_bw() +
  scale_y_continuous(expand = expansion(mult=c(0,0))) + 
  scale_x_continuous(expand = expansion(add=c(0,0)))
dev.off()
# 图3 c
# https://blog.csdn.net/tandelin/article/details/87887368
Cairo::CairoTIFF(file="Figure2C.tiff", width=8, height=8,units="in",dpi=150)
ggplot(data = countriesMapTop10,aes(x='',y=Freq,fill= Tab)) +
  # 生成柱状图
  geom_bar(stat = "identity")+
  #生成环
  coord_polar(theta = "y")
dev.off()
# 图4 d
# https://www.cnblogs.com/muchen/p/5386296.html
# https://zhuanlan.zhihu.com/p/250971770
# 准备国家发表年份计数
counList <-as.array( as.character( countriesMapTop10$Tab))
counSizeNew <-data.frame(coun = c('china'),size=c(10),year=c(2010))
for (year in c(2012:2022)) {
  for (coun in counList) {
    print(year)
    print(coun)
    Mtemp<- M[which(M$PY==year),]
    resultsTemp <- biblioAnalysis(Mtemp, sep = ";")
    CountriesTemp <-as.data.frame(resultsTemp$Countries)
    sincoun <-CountriesTemp[which(CountriesTemp$Tab==coun),]
    counttt<- ifelse(length(sincoun)>0,sincoun[1,2],0)
    myList<-list(coun,counttt,year)    
    counSizeNew<-rbind(counSizeNew,myList) 
  }
}
# 删除默认的2010年数据
counSizeNew <- counSizeNew[which(counSizeNew$year!=2010),]
counSizeNew$size<- ifelse(is.na(counSizeNew$size),0,counSizeNew$size)
# 基函数
Cairo::CairoTIFF(file="Figure2d.tiff", width=8, height=8,units="in",dpi=150)
ggplot(counSizeNew, aes(x = year, y = size, fill = coun)) +
  # 面积图函数
  geom_area()
dev.off()
#+
  # 调色标尺：breaks反转图例顺序
 # scale_fill_brewer(palette = "Blues", breaks = rev(levels(counSizeNew$coun)))

# table1 介绍了发文国家 占比 被引次数 平均被引次数 和H 指数 （自己造）
# S$MostProdCountries  国家发文量
# 一定要查看数据 去除空格 tmd 这个破问题处理了半天了
TCperCountries<-S$TCperCountries
MostProdCountries<-S$MostProdCountries


colnames(TCperCountries) <-c('Country','TotalCitations','AverageArticleCitations')
TCperCountries$Country<-trim(TCperCountries$Country)
TCperCountries$AverageArticleCitations<-trim(TCperCountries$AverageArticleCitations)
TCperCountries$TotalCitations<-trim(TCperCountries$TotalCitations)
MostProdCountries$Country<-trim(MostProdCountries$Country)
papertable1 <- left_join(MostProdCountries,TCperCountries ,by = c('Country'='Country'))


papertable1$Country<-as.character(papertable1$Country)
papertable1$Articles<-as.numeric(papertable1$Articles)
papertable1$Freq<-as.numeric(papertable1$Freq)
papertable1$SCP<-as.numeric(papertable1$SCP)
papertable1$MCP<-as.numeric(papertable1$MCP)
papertable1$MCP_Ratio<-as.numeric(papertable1$MCP_Ratio)
papertable1$TotalCitations<-as.numeric(papertable1$TotalCitations)
papertable1$AverageArticleCitations<-as.numeric(papertable1$AverageArticleCitations)
papertable1<-dplyr::mutate(papertable1,Percentage = Freq*100)
# 组合表1 数据
colnames(papertable1)[2]<- c('Article count')
colnames(papertable1)[9]<- c('Percentage (%, N/2075)')
colnames(papertable1)[2]<- c('Article count')
colnames(papertable1)[2]<- c('Article count')
# 删除没用列
papertable1<- papertable1[,-4]
papertable1<- papertable1[,-4]
papertable1<- papertable1[,-3]
papertable1<- papertable1[,-3]

colnames(papertable1)[3]<- c('Citation')
colnames(papertable1)[4]<- c('Average citation')
papertable1<- dplyr::select(papertable1,'Country','Article count','Percentage (%, N/2075)','Citation','Average citation')

#create an html table 
# tableHTML(papertable1)
#and to export in a file
write_tableHTML(tableHTML(papertable1), file = 'table1.html')

# 合作国家和合作单位

# 国家
MCountry <- metaTagExtraction(M, Field = "AU_CO", sep = ";")
NetMatrixCountrycollaboration <- biblioNetwork(MCountry, analysis = "collaboration", network = "countries", sep = ";")
# Plot the network
Cairo::CairoTIFF(file="Figure3A.tiff", width=8, height=8,units="in",dpi=150)
# net=networkPlot(NetMatrixCountry, n = 10, Title = "Country Collaboration", type = "sphere", size=TRUE, remove.multiple=FALSE,labelsize=0.7,cluster="none")
netCountry=networkPlot(NetMatrixCountrycollaboration, n=25, size=TRUE, remove.multiple = FALSE, Title='Country Collaboration',
            type='sphere')
plot(netCountry$graph)
dev.off()
# 单位
MUnit <- metaTagExtraction(M, Field = "AU_UN", sep = ";")
NetMatrixUnitcollaboration <- biblioNetwork(MUnit, analysis = "collaboration", network = "universities", sep = ";")
# Plot the network
Cairo::CairoTIFF(file="Figure3B.tiff", width=25, height=25,units="in",dpi=150)
netUnit<-networkPlot(NetMatrixUnitcollaboration, n = 35, Title = "Unit Collaboration", label = TRUE,
                    edgesize = 2, type = "fruchterman", size=3,
                    remove.multiple=F,labelsize=0.8,cluster="optimal")
plot(netUnit$graph)
dev.off()


# table2 top 10 十大机构发文

Affiliations<-as.data.frame(results$Affiliations)
Affiliations$AFF<- as.character(Affiliations$AFF)
# skim(Affiliations)
sum(Affiliations$Freq)
Affiliations<- Affiliations[c(1:10),]
Affiliations$Country <- 'China'
colnames(Affiliations)[1]<- c('Institution')
colnames(Affiliations)[2]<- c('Articlecount')
Affiliations<-dplyr::mutate(Affiliations,Percentage = Articlecount/2075*100)
write_tableHTML(tableHTML(Affiliations), file = 'table2.html')

# Top 10 productive journals 十大期刊
MostRelSources<-S$MostRelSources
colnames(MostRelSources)[1]<- c('Journal')
colnames(MostRelSources)[2]<- c('Articlecount')
MostRelSources$Articlecount<- as.numeric( as.character(MostRelSources$Articlecount))

MostRelSources<-dplyr::mutate(MostRelSources,Percentage = Articlecount/2075*100)
jourif <-c(11.061,3.748,10.633,11.092,6.064,4.967,5.395,8.457,15.304,6.208)
MostRelSources$IF <-jourif
write_tableHTML(tableHTML(MostRelSources), file = 'table3.html')

# 期刊共同被引
# 图片放一边
#A <- cocMatrix(M, Field = "CR", sep = ".  ")
#NetMatrix <- biblioNetwork(M, analysis = "co-citation", network = "references", sep = ";")

#NetMatrix <- biblioNetwork(M, analysis = "co-citation", network = "sources", sep = ";")

# Plot the network
# net=networkPlot(NetMatrix, n = 30, Title = "Co-Citation Network", type = "fruchterman", size=T, remove.multiple=FALSE, labelsize=0.7,edgesize = 5)


# 作者合作网络

## 期刊关系  需要用带参文的wos 导出文件才可以
CR_SO <- metaTagExtraction(M, Field = "CR_SO", sep = ";")
NetMatrixUnit <- biblioNetwork(CR_SO, analysis = "coupling", network = "sources", sep = ";")
# Plot the network
Cairo::CairoTIFF(file="Figure4A.tiff", width=25, height=25,units="in",dpi=150)
jourcoupling<-networkPlot(NetMatrixUnit, n = 35, Title = "jour coupling", label = TRUE,
                     edgesize = 2, type = "fruchterman", size=3,
                     remove.multiple=F,labelsize=0.8,cluster="optimal")
plot(jourcoupling$graph)
dev.off()

# table 4 5 放一边
# table4 十大 共同被引期刊
M$TotalCitation<-as.list(results$TotalCitation)
# table(M$TotalCitation)

# table5  十大 具有代表性的研究领域

# table6 十大作者

MostProdAuthors<-S$MostProdAuthors
MostProdAuthors<-MostProdAuthors[,-3]
MostProdAuthors<-MostProdAuthors[,-3]
MostProdAuthors<-as.data.frame(MostProdAuthors)
MostProdAuthors$Articles<- as.numeric(MostProdAuthors$Articles)
MostProdAuthors<-dplyr::mutate(MostProdAuthors,Percentage = Articles/2075*100)
write_tableHTML(tableHTML(MostProdAuthors), file = 'table6.html')


# Figure5A.tiff
NetMatrixAuthorcollaboration <- biblioNetwork(M, analysis = "collaboration", network = "authors", sep = ";")
# Plot the network
Cairo::CairoTIFF(file="Figure5A.tiff", width=8, height=8,units="in",dpi=150)
netAuthorcollaboration<-networkPlot(NetMatrixAuthorcollaboration, normalize="association", weighted=T, n = 30, Title = "authors collaboration", type = "fruchterman", size=T,edgesize = 5,labelsize=0.7)
plot(netAuthorcollaboration$graph)
dev.off()

# Figure5B.tiff
# NetMatrixAuthorcocitation <- biblioNetwork(M, analysis = "co-citation", network = "authors", sep = ";")
# # Plot the network
# Cairo::CairoTIFF(file="Figure5A.tiff", width=8, height=8,units="in",dpi=150)
# netAuthorcollaboration<-networkPlot(NetMatrixAuthorcollaboration, normalize="association", weighted=T, n = 30, Title = "authors collaboration", type = "fruchterman", size=T,edgesize = 5,labelsize=0.7)
# plot(netAuthorcollaboration$graph)
# dev.off()


# table7  基金信息 需要很详细自己去根据FU 统计 很麻烦 一堆事
# table(M$FU)

# table8 
table(M$DT)
colnames(M)
Mtable8Re<- M[which(M$DT=='REVIEW'),c('DT','TI','AU','SO','PY','TotalCitation')]
Mtable8Re$TotalCitation <- as.numeric(Mtable8Re$TotalCitation)
Mtable8Re <-arrange(Mtable8Re, -TotalCitation)

Mtable8ReTOP5 <-  Mtable8Re[C(1:5),]
write_tableHTML(tableHTML(Mtable8ReTOP5), file = 'table8.html')


# table9  这个是被引全部数量累加不是 co-citation 没找到
Mtable8ReF<- M[,c('DT','TI','AU','SO','PY','TotalCitation')]
Mtable8ReF$TotalCitation <- as.numeric(Mtable8ReF$TotalCitation)
Mtable8ReF <-arrange(Mtable8ReF, -TotalCitation)
Mtable8RefTOP5 <-  Mtable8ReF[C(1:5),]
write_tableHTML(tableHTML(Mtable8RefTOP5), file = 'table9.html')


# 2023年11月2日15:36:26 先这样这片文章 下面做另一篇


